import type { FC } from 'react';
import { useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react';
import { allGet } from '@/services/pc';
import { useHistory } from 'umi';
import { isVideo } from '@/utils';
import { message, Spin, Modal } from 'antd';
import { useAliyunUpload } from '@/pages/pc/components/Upload/AliyunVideoUpload';
import ImageModal from './image-modal';
import VideoModal from './video-modal';
import LinkVideoModal from './link-video-modal';

const Index: FC<any> = forwardRef(
  (
    {
      aliyunVideoRegion = 'cn-shanghai',
      aliyunVideoUserId = '241647822948555848',
      getAliyunAuth,
      refreshAliyunAuth,
      ...props
    },
    ref,
  ) => {
    const tinymceRef = useRef<any>();
    const [visible, setVisible] = useState(false);
    const [videoVisible, setVideoVisible] = useState(false);
    const [linkVideoVisible, setLinkVideoVisible] = useState(false);

    const uploadVideo2PhpTimer = useRef<any>();
    const classDetailPicVideoRef = useRef<any>();
    const uploadUrlRef = useRef('');
    const [loading, setLoading] = useState(false);
    const [isFull, setIsFull] = useState(false);
    const handleUploadSuccess = async (file, field) => {
      if (isVideo(file.name)) {
        file.videoId = file?.response?.videoId;
        const response = await allGet({
          params: {
            version: 'pc1.0',
            mod: 'video',
            do: 'aliyun',
            action: 'upload',
            type: 'course',
            field,
            aid: file.aid || 0,
            filename: file.name,
            videoid: file.videoId,
          },
        });
        if (!response.success) {
          clearTimeout(uploadVideo2PhpTimer.current);
          return;
        }
        file.aid = response?.data?.attachid;
        if (response.success && response.data.attachment) {
          clearTimeout(uploadVideo2PhpTimer.current);
          file.attachment = response.data.attachment;
          console.log(file);
          uploadUrlRef.current = response.data.attachment;
          // if (field === 'message') {
          //   classDetailPicVideoRef.current.push({ ...file });
          // }
        } else {
          setTimeout(() => {
            handleUploadSuccess(file, field);
          }, 500);
        }
      } else {
        if (field === 'message') {
          classDetailPicVideoRef.current.push({ ...file });
        }
      }
    };

    const toggleFull = () => {
      if (document.fullscreenElement) {
        document.exitFullscreen();
        setIsFull(false);
      } else {
        document.querySelector('#tiny-id-container')?.requestFullscreen();
        setIsFull(true);
      }
    };
    const init = async () => {
      tinymce.init({
        selector: '#tiny-d',
        // icons_url: PUBLIC_PATH + 'custom/icons.js',
        icons: 'custom',
        branding: false,
        elementpath: false,
        height: '100%',
        language: 'zh-Hans',
        plugins: 'image imagetools media emoticons link unlink autolink lists advlist fullscreen', // bullist numlist
        toolbar:
          'fontsizeselect bold underline forecolor backcolor | alignleft aligncenter alignright | link unlink autolink  blockquote undo redo | emoticons lImage lVideo lLinkVideo | fullscreen',
        skin: 'CUSTOM',
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px',
        fontsize_input_default_unit: 'px',
        color_default_background: 'Yellow',
        color_default_foreground: 'White',
        custom_colors: true,
        menubar: false,
        resize: false,
        // toolbar_mode: 'scrolling',
        content_css: 'CUSTOM',
        content_style:
          'img {max-width:100%;}p {margin: 0px;}a {color: #4EE9FF}body {background-color: #192C53} .tox .tox-statusbar{background-color: #192C53}',
        images_upload_url: props.action,
        // image_dimensions: false,
        images_upload_handler: (blobInfo, succFun, failFun) => {
          const file = blobInfo.blob(); //转化为易于理解的file对象
          const xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open('POST', props.action);
          xhr.onload = function () {
            if (xhr.status != 200) {
              failFun('HTTP Error: ' + xhr.status);
              return;
            }
            const json = JSON.parse(xhr.responseText);
            console.log(json);
            if (!json.success) {
              failFun('Invalid JSON: ' + xhr.responseText);
              return;
            }
            succFun(json.data.url);
          };
          const formData = new FormData();
          if (props.payload) {
            Object.keys(props.payload).forEach((key) => {
              formData.append(key, props.payload[key]);
            });
          }
          formData.append(props.name, file, file.name); //此处与源文档不一样
          xhr.send(formData);
        },
        setup: (editor) => {
          editor.ui.registry.addButton('lImage', {
            // text: '图片',
            icon: 'image',
            onAction: () => {
              setVisible(true);
            },
          });
          editor.ui.registry.addButton('lVideo', {
            // text: '视频',
            icon: 'embed',
            onAction: () => {
              setVideoVisible(true);
            },
          });
          editor.ui.registry.addButton('lLinkVideo', {
            // text: '外链',
            tip: '外链',
            icon: 'embed-page',
            onAction: () => {
              setLinkVideoVisible(true);
            },
          });
        },
      });
    };

    const onOk = (images) => {
      let str: string = '';
      images?.forEach((item) => {
        str += `<img src="${item.response?.data?.url}" alt="${item.name}" data-mce-src="${item.response?.data?.url}">`;
      });
      tinymce.get('tiny-d').insertContent(str);
      setVisible(false);
    };
    const onVideoOk = (videos) => {
      let str: string = '';
      videos?.forEach((item) => {
        str += `
            <video width="100%" height="100%" controls="controls"><source src="${item.url}" type="video/mp4"></video>
        `;
      });
      tinymce.get('tiny-d').insertContent(str);
      setVideoVisible(false);
    };
    const onLinkVideoOk = (videos) => {
      videos?.forEach((item, index) => {
        tinymce.get('tiny-d').insertContent(`
            <iframe style="width: 100%; height: 663px" src="${item.url}" scrolling="no" border="0" frameBorder="no" framespacing="0" allowfullscreen="true"/>
        `);
        // if(index < videos.lenth - 1){
        //   tinymce.get('tiny-d').insertContent(`
        //    <p</p>
        // `)
        // }
      });

      setLinkVideoVisible(false);
    };

    useImperativeHandle(ref, () => ({
      getValue: () => {
        return tinymce.get('tiny-d').getContent();
      },
      setValue: async (html: string) => {
        setTimeout(async () => {
          if (tinymce.get('tiny-d')) {
            tinymce.get('tiny-d').setContent(html);
          } else {
            await init();
            tinymce.get('tiny-d').setContent(html);
          }
        }, 500);

        // setTimeout(async () => {
        //   if (tinyMCE.editors['tiny-d']) {
        //     tinyMCE.editors['tiny-d'].setContent(html);
        //   } else {
        //     await init();
        //     tinyMCE.editors['tiny-d'].setContent(html);
        //   }
        // }, 500);
      },
    }));

    useEffect(() => {
      tinymce.remove('#tiny-d');
      init();
      return () => {
        tinymce.remove('#tiny-d');
      };
    }, []);
    return (
      <div
        id="tiny-id-container"
        style={{
          position: 'relative',
          height: isFull ? '100vh' : 600,
          borderRadius: 8,
          overflow: 'hidden',
        }}
      >
        <div id="tiny-d" ref={tinymceRef}>
          {props.children}
        </div>
        ,
        <ImageModal
          visible={visible}
          payload={props.payload}
          name={props.name}
          action={props.action}
          getContainer={isFull ? () => document.querySelector('#tiny-id-container') : undefined}
          onCancel={() => {
            setVisible(false);
          }}
          onOk={onOk}
        />
        <VideoModal
          visible={videoVisible}
          payload={props.payload}
          name={props.name}
          action={props.action}
          getContainer={isFull ? () => document.querySelector('#tiny-id-container') : undefined}
          aliyunVideoRegion={aliyunVideoRegion}
          aliyunVideoUserId={aliyunVideoUserId}
          getAliyunAuth={getAliyunAuth}
          refreshAliyunAuth={refreshAliyunAuth}
          onCancel={() => {
            setVideoVisible(false);
          }}
          onOk={onVideoOk}
        />
        <LinkVideoModal
          visible={linkVideoVisible}
          getContainer={isFull ? () => document.querySelector('#tiny-id-container') : undefined}
          onCancel={() => {
            setLinkVideoVisible(false);
          }}
          onOk={onLinkVideoOk}
        />
        <div
          style={{
            display: loading ? 'flex' : 'none',
            background: 'rgba(0,0,0, 0.3)',
            alignItems: 'center',
            justifyContent: 'center',
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: 1300,
          }}
        >
          <Spin tip="上传中，请等待..." />
        </div>
      </div>
    );
  },
);
export default Index;
